package maple.thelittleredbook.common.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.util.Map;

@Slf4j
@Service
public class EmailService {

    private final JavaMailSender mailSender;
    private final TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Value("${app.admin.super-admin-email}")
    private String superAdminEmail;

    public EmailService(JavaMailSender mailSender, TemplateEngine templateEngine) {
        this.mailSender = mailSender;
        this.templateEngine = templateEngine;
    }

    /**
     * 发送HTML模板邮件
     *
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param templateName 模板名称
     * @param variables 模板变量
     * @return 是否发送成功
     */
    public boolean sendTemplateEmail(String to, String subject, String templateName, Map<String, Object> variables) {
        try {
            // 准备邮件内容
            Context context = new Context();
            if (variables != null) {
                variables.forEach(context::setVariable);
            }
            String htmlContent = templateEngine.process(templateName, context);

            // 创建邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(fromEmail);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);

            // 发送邮件
            mailSender.send(message);
            log.info("邮件已发送至: {}", to);
            return true;
        } catch (MessagingException e) {
            log.error("发送邮件失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 发送验证码邮件（用户注册）
     *
     * @param to 收件人邮箱
     * @param verificationCode 验证码
     * @param purpose 用途（注册/重置密码）
     * @return 是否发送成功
     */
    public boolean sendVerificationCodeEmail(String to, String verificationCode, String purpose) {
        String subject;
        String templateName;

        if ("email_verification".equals(purpose)) {
            subject = "小红书 - 邮箱验证码";
            templateName = "email-verification";
        } else if ("password_reset".equals(purpose)) {
            subject = "小红书 - 密码重置验证码";
            templateName = "password-reset";
        } else {
            log.error("不支持的验证码用途: {}", purpose);
            return false;
        }

        Map<String, Object> variables = Map.of(
                "verificationCode", verificationCode,
                "expirationMinutes", 10
        );

        return sendTemplateEmail(to, subject, templateName, variables);
    }

    /**
     * 发送管理员申请邮件给超级管理员
     *
     * @param applicantEmail 申请人邮箱
     * @param applicantUsername 申请人用户名
     * @param userId 申请人用户ID
     * @param applicantBio 申请人简介
     * @return 是否发送成功
     */
    public boolean sendAdminApplicationEmail(String applicantEmail, String applicantUsername, Long userId, String applicantBio) {
        String subject = "小红书 - 管理员申请待审核";
        String templateName = "admin-application";

        Map<String, Object> variables = Map.of(
                "applicantEmail", applicantEmail,
                "applicantUsername", applicantUsername,
                "userId", userId,
                "applicantBio", applicantBio != null ? applicantBio : ""
        );

        return sendTemplateEmail(superAdminEmail, subject, templateName, variables);
    }

    /**
     * 发送管理员审核结果邮件
     *
     * @param applicantEmail 申请人邮箱
     * @param applicantUsername 申请人用户名
     * @param approved 是否通过（true=通过，false=拒绝）
     * @param reviewerUsername 审核人用户名
     * @param rejectReason 拒绝原因（仅拒绝时使用）
     * @return 是否发送成功
     */
    public boolean sendAdminReviewResultEmail(String applicantEmail, String applicantUsername,
                                              boolean approved, String reviewerUsername, String rejectReason) {
        String subject;
        String templateName;

        if (approved) {
            subject = "小红书 - 管理员申请已通过";
            templateName = "admin-approval-success";
        } else {
            subject = "小红书 - 管理员申请未通过";
            templateName = "admin-approval-rejected";
        }

        Map<String, Object> variables = Map.of(
                "applicantUsername", applicantUsername,
                "reviewerUsername", reviewerUsername,
                "approved", approved,
                "rejectReason", rejectReason != null ? rejectReason : ""
        );

        return sendTemplateEmail(applicantEmail, subject, templateName, variables);
    }
}